<template>
  <main-card-admin title="教师管理" :loading="globalLoading" :show-screen-space="false" :main-body-style-obj="{ paddingTop: '12px' }">
    <template #tool-btn>
      <a-button v-auth="'admin-teacher-manage'" type="primary" @click="openTeacherForm">新增教师</a-button>
    </template>
    <div class="content-wrap">
      <staff-constitute v-model:selected-keys="selectedKeys" @treeSelect="treeSelect" />
      <div class="table-wrap">
        <div class="flex mb-20">
          <a-input v-model:value="pageForm.name" class="w-328px" placeholder="教师姓名、手机号码" @keyup.enter="getDataList({ offset: 1 })">
            <template #prefix> <i class="iconfont icon-search-line"></i> </template>
          </a-input>
          <a-button v-auth="'admin-teacher-manage'" class="ml-auto" @click="() => (batchDisposeVisible = !batchDisposeVisible)">
            批量操作
          </a-button>
        </div>
        <GTable
          :action-width="60"
          :columns="columns"
          :data="dataList"
          :page-form="pageForm"
          :loading="loading"
          row-key="id"
          :action-option="actionOption"
          :row-selection="rowSelection"
          @getDataList="getDataList"
        >
          <template #role="{ record }">
            <ul class="role-wrap">
              <li v-for="role in record.roleNames" :key="role">{{ role }}</li>
            </ul>
          </template>
          <template #organization="{ record }">
            <a-tooltip placement="left">
              <template #title v-if="record.orgList?.[0]?.fullOrgName">
                <div v-html="record.orgList?.map((item: any) => item?.fullOrgName)?.join('<br />')"></div>
              </template>
              <span :title="record.orgList?.map((item: any) => item?.name)?.join('、')">
                {{ record.orgList?.map((item: any) => item?.name)?.join('、') }}
              </span>
            </a-tooltip>
          </template>
        </GTable>
      </div>
    </div>
  </main-card-admin>
  <g-batch-dispose v-model:data-list="rowSelection.selectedRowKeys" :total="pageForm.total" :visible="batchDisposeVisible">
    <a-button :disabled="!rowSelection.selectedRowKeys.length" :loading="batchOrgLoading" @click="openInstallOrgForm">
      设置所属组织
    </a-button>
    <a-button
      v-auth="'admin-teacher-manage'"
      :disabled="!rowSelection.selectedRowKeys.length"
      :loading="batchDeleteLoading"
      @click="batchDeletionOfIDs"
    >
      批量删除
    </a-button>
  </g-batch-dispose>
  <teacher-form ref="teacherFormRef" @submit="teacherFormSubmit" />
  <install-org-form ref="installOrgFormRef" @submit="installOrgFormSubmit" />
</template>

<script setup lang="ts">
  import { message, Modal } from 'ant-design-vue'
  import { computed, createVNode, ref } from 'vue'
  import { useRequest } from 'vue-request'

  import WarnIcon from '@/components/icon/IconWarning/index.vue'
  import useList from '@/hooks/use-list'
  import { teacherManageApi } from '@/services/api'

  import StaffConstitute from '../components/StaffConstitute.vue'
  import InstallOrgForm from './components/InstallOrgForm.vue'
  import TeacherForm from './components/TeacherForm.vue'

  const teacherFormRef = ref<InstanceType<typeof TeacherForm>>()
  const installOrgFormRef = ref<InstanceType<typeof InstallOrgForm>>()
  const batchDisposeVisible = ref(false)
  const selectedKeys = ref<string[] | number[]>(['1'])

  const rowSelection = ref({
    checkStrictly: false,
    selectedRowKeys: [] as (string | number)[],
    onChange: (selectedRowKeys: (string | number)[]) => {
      rowSelection.value.selectedRowKeys = selectedRowKeys
    }
  })

  const columns = [
    {
      title: '姓名',
      dataIndex: 'username',
      width: 200
    },
    {
      title: '工号',
      dataIndex: 'number',
      width: 200
    },
    {
      title: '手机号码',
      dataIndex: 'tel',
      width: 200
    },
    {
      title: '所属组织',
      dataIndex: 'os',
      slot: 'organization',
      width: 200
    },
    {
      title: '角色',
      dataIndex: 'role',
      slot: 'role'
    }
  ]

  const actionOption = {
    more: [
      {
        text: '编辑',
        auth: 'admin-teacher-manage',
        onClick: (r: any) => openUpdateTeacherForm(r)
      },
      {
        text: '重置密码',
        auth: 'admin-teacher-reset',
        onClick: (r: any) => handleResetPassword(r)
      },
      {
        text: '删除',
        auth: 'admin-teacher-manage',
        onClick: (r: any) => handleDelete(r)
      }
    ]
  }

  const { pageForm, loading, dataList, getDataList } = useList<any, any>(
    teacherManageApi.list,
    {
      columns: '',
      limit: 10,
      orgId: '',
      name: '',
      offset: 1,
      order: '',
      total: 0
    },
    {
      afterCallback: () => {
        rowSelection.value.selectedRowKeys = []
      }
    }
  )
  getDataList()

  const refresh = () => {
    getDataList()
    batchDisposeVisible.value = false
    rowSelection.value.selectedRowKeys = []
  }

  //全局Loading
  const globalLoading = computed(() => {
    return loading.value
  })

  const treeSelect = (selectedKeys: any[]) => {
    console.log(selectedKeys, 'selectedKeys')
    getDataList({
      offset: 1,
      orgId: selectedKeys[0]
    })
  }

  const openTeacherForm = () => {
    teacherFormRef.value?.open('新建教师')
  }

  const openUpdateTeacherForm = async (r: any) => {
    const { data } = await teacherManageApi.getDetailById({}, { urlParams: { id: r.id } })
    const params = {
      id: data.id,
      number: data.number,
      tel: data.tel,
      username: data.username,
      orgIds: data.orgList.map((item: any) => item.id),
      roleIds: data.roles.map((item: any) => item.id)
    }
    teacherFormRef.value?.open('编辑教师', params)
  }

  const { runAsync: runAdd } = useRequest(teacherManageApi.add)
  const { runAsync: runUpdate } = useRequest(teacherManageApi.update)
  const teacherFormSubmit = async (state: any) => {
    teacherFormRef.value?.changeConfirmLoading(true)
    try {
      const isUpdate = teacherFormRef.value?.modalTitle === '编辑教师'
      console.log(state, 'state')
      const params = {
        ...state,
        orgIds: state.orgIds?.map((item: any) => item?.value ?? item)
      }
      if (isUpdate) {
        await runUpdate(params, { isAddUid: true })
      } else {
        await runAdd(params, { isAddUid: true })
      }
      refresh()
      message.success('操作成功')
      teacherFormRef.value?.close()
    } catch (error) {
    } finally {
      teacherFormRef.value?.changeConfirmLoading(false)
    }
  }

  // 重置密码
  const handleResetPassword = (r: any) => {
    console.log('重置密码', r)
    Modal.confirm({
      title: '确认重置密码？',
      content: '密码将被重置为“12345678”，重置后首次登录将为要求用户重新设置新密码。',
      centered: true,
      icon: createVNode(WarnIcon),
      async onOk() {
        await teacherManageApi.resetPws({}, { urlParams: { id: r.id } })
        message.success('操作成功')
      },
      onCancel() {
        console.log('取消')
      }
    })
  }

  // 单个删除
  const handleDelete = (r: any) => {
    console.log('删除', r)
    const content = createVNode('div', null, [
      createVNode('span', null, '教师被删除后将无法登录系统'),
      createVNode('span', { style: 'color:rgba(17, 22, 31, 0.52);font-size: 12px;' }, '（教学活动数据将保留）'),
      createVNode('span', null, '，请确认操作')
    ])
    Modal.confirm({
      title: '确认删除？',
      content,
      centered: true,
      icon: createVNode(WarnIcon),
      async onOk() {
        await teacherManageApi.del({}, { urlParams: { id: r.id } })
        refresh()
        message.success('操作成功')
      },
      onCancel() {
        console.log('取消')
      }
    })
  }

  // 批量删除
  const { loading: batchDeleteLoading, runAsync: runDelList } = useRequest(teacherManageApi.delList)
  const batchDeletionOfIDs = async () => {
    await runDelList({}, { data: rowSelection.value.selectedRowKeys })
    refresh()
    message.success('操作成功')
  }

  // 设置组织
  const { loading: batchOrgLoading, runAsync: runBatchSetOrg } = useRequest(teacherManageApi.batchSetOrg)
  const openInstallOrgForm = () => {
    installOrgFormRef.value?.open('设置所属组织')
  }
  const installOrgFormSubmit = async (state: any) => {
    const orgIds = state.orgIds?.map((item: any) => item?.value ?? item) || []
    await runBatchSetOrg({ ids: rowSelection.value.selectedRowKeys, orgIds: orgIds })
    refresh()
    installOrgFormRef.value?.close()
    message.success('操作成功')
  }
</script>

<style lang="less" scoped>
  .content-wrap {
    display: flex;
    width: 100%;
    min-height: 0;
    border-radius: 8px;
    flex: 1;
    flex-shrink: 0;
    gap: 0 16px;

    .table-wrap {
      flex: 1;
    }

    .role-wrap {
      display: flex;
      gap: 0 8px;

      > li {
        padding: 0 6px;
        max-width: fit-content;
        height: 22px;
        line-height: 22px;
        font-size: 12px;
        color: rgba(21, 23, 27, 0.95);
        background: #fff;
        border: 1px solid #e8e9eb;
        border-radius: 5px;
      }
    }
  }
</style>
